/**
 *  var mapping = {
        "按钮索引": "自定义键名称"
    }
    var ketMapping = {
        4: 'L1',
        6: 'L2',

        5: 'R1',
        7: 'R2',

        8: 'START',
        9: 'SELECT',

        10: 'axes-1',
        11: 'axes-2',

        1: 'A',
        2: 'B',

        0: 'AA',
        3: 'BB',
    }
    var _pad = new PAD(ketMapping, function (button) {
        console.log('按下:', button);
    }, function (button) {
        console.log('抬起:', button)
    });
    _pad.connected = function (pad) {
        $('#info').text('连接:'+pad.id)
    }
    _pad.dconnected=function(pad){
        $('#info').text('移除:'+pad.id)
    }
    _pad.Listener(); 
 */
/**
 * 游戏手柄
 * @param {object} mapping          自定义按键映射
 * @param {function} onPress        按钮按下事件
 * @param {function} onRelease      按钮抬起事件
 * @param {bool} continuous         是否连续发生按钮按下事件
 */
var PAD = function (mapping, onPress, onRelease, continuous) {
    var pullInterval = null;
    var keyDown = {};
    var axesDown = {};
    var sended = {};
    this.connected = function () { };
    this.dconnected = function () { };
    this.Listener = function (raf) {
        raf = raf || 16;
        var self = this;
        self.onPress = onPress;
        self.onRelease = onRelease;
        window.addEventListener('gamepaddisconnected', function (e) {
            clearInterval(pullInterval);
            self.gamepad = null;
            self.dconnected(e.gamepad);
        });

        window.addEventListener('gamepadconnected', function (e) {
            self.connected(e.gamepad);
            self.gamepad = e.gamepad;
            pullInterval = setInterval(function () {
                self.getKey();
            }, raf);
        });
    }
    this.getKey = function () {
        var self = this;
        var pad = navigator.getGamepads()[self.gamepad.index];
        if (pad) {
            for (var index in mapping) {
                index = parseInt(index)
                var key = mapping[index];
                var button = pad.buttons[index];
                var oldState = keyDown[index];
                keyDown[index] = button.pressed;
                if (button && button.pressed) {
                    if (continuous === true) {
                        self.onPress({ keyCode: index, 'key': key, button });
                    } else {
                        if (!sended[key]) {
                            sended[key] = true;
                            self.onPress({ keyCode: index, 'key': key, button });
                        }
                    }
                } else if (button && !button.pressed && oldState) {
                    delete sended[key];
                    self.onRelease({ keyCode: index, 'key': key, button });
                }
            }
            if (pad.axes[1] < -0.5) {
                axesDown['ArrowUp'] = true;
                if (continuous === true) {
                    self.onPress({ 'key': 'ArrowUp', keyCode: 38, axes: pad.axes });
                } else {
                    if (!sended['ArrowUp']) {
                        sended['ArrowUp'] = true;
                        self.onPress({ 'key': 'ArrowUp', keyCode: 38, axes: pad.axes });
                    }
                }
            }
            else if (axesDown['ArrowUp']) {
                delete sended['ArrowUp'];
                axesDown['ArrowUp'] = false;
                self.onRelease({ 'key': 'ArrowUp', keyCode: 38, axes: pad.axes });
            }


            if (pad.axes[1] > 0.5) {
                axesDown['ArrowDown'] = true;
                if (continuous === true) {
                    self.onPress({ 'key': 'ArrowDown', keyCode: 40, axes: pad.axes });
                } else {
                    if (!sended['ArrowDown']) {
                        sended['ArrowDown'] = true;
                        self.onPress({ 'key': 'ArrowDown', keyCode: 40, axes: pad.axes });
                    }
                }

            } else if (axesDown['ArrowDown']) {
                delete sended['ArrowDown'];
                axesDown['ArrowDown'] = false;
                self.onRelease({ 'key': 'ArrowDown', keyCode: 40, axes: pad.axes });
            }


            if (pad.axes[0] < -0.5) {
                axesDown['ArrowLeft'] = true;
                if (continuous === true) {
                    self.onPress({ 'key': 'ArrowLeft', keyCode: 37, axes: pad.axes });
                } else {
                    if (!sended['ArrowLeft']) {
                        sended['ArrowLeft'] = true;
                        self.onPress({ 'key': 'ArrowLeft', keyCode: 37, axes: pad.axes });
                    }
                }
            } else if (axesDown['ArrowLeft']) {
                delete sended['ArrowLeft'];
                axesDown['ArrowLeft'] = false;
                self.onRelease({ 'key': 'ArrowLeft', keyCode: 37, axes: pad.axes });
            }

            if (pad.axes[0] > 0.5) {
                axesDown['ArrowRight'] = true;
                if (continuous === true) {
                    self.onPress({ 'key': 'ArrowRight', keyCode: 39, axes: pad.axes });
                } else {
                    if (!sended['ArrowRight']) {
                        sended['ArrowRight'] = true;
                        self.onPress({ 'key': 'ArrowRight', keyCode: 39, axes: pad.axes });
                    }
                }
            } else if (axesDown['ArrowRight']) {
                delete sended['ArrowRight'];
                axesDown['ArrowRight'] = false;
                self.onRelease({ 'key': 'ArrowRight', keyCode: 39, axes: pad.axes });
            }
        }
    }
}